package com.example.xncs;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.database.Cursor;
import android.net.Uri;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.InputStream;
import java.io.IOException;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int PERMISSION_REQUEST_CODE = 100;
    private static final int APP_SELECTION_REQUEST_CODE = 200;

    private LinearLayout layoutAppSelection;
    private Button btnSelectApp, btnBrowse, btnAutoPlay;
    private SeekBar seekBarInterval;
    private TextView tvInterval, tvPermissionHint, tvSelectedApp;
    private RecyclerView recyclerViewPreview;

    private List<AppInfo> allAppList;
    private List<ImageItem> imageList;
    private ImagePreviewAdapter previewAdapter;

    private int currentSwitchInterval = 3;
    private AppInfo selectedApp = null;
    private Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();
        checkPermissions();
        setupSeekBar();
        setupButtons();
    }

    private void initViews() {
        layoutAppSelection = findViewById(R.id.layoutAppSelection);
        btnSelectApp = findViewById(R.id.btnSelectApp);
        btnBrowse = findViewById(R.id.btnBrowse);
        btnAutoPlay = findViewById(R.id.btnAutoPlay);
        seekBarInterval = findViewById(R.id.seekBarInterval);
        tvInterval = findViewById(R.id.tvInterval);
        tvPermissionHint = findViewById(R.id.tvPermissionHint);
        tvSelectedApp = findViewById(R.id.tvSelectedApp);
        recyclerViewPreview = findViewById(R.id.recyclerViewPreview);

        // 设置预览RecyclerView
        recyclerViewPreview.setLayoutManager(new GridLayoutManager(this, 3));
        imageList = new ArrayList<>();
        previewAdapter = new ImagePreviewAdapter(this, imageList);
        recyclerViewPreview.setAdapter(previewAdapter);
    }

    private void checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
            tvPermissionHint.setVisibility(View.VISIBLE);
        } else {
            tvPermissionHint.setVisibility(View.GONE);
            loadAllInstalledApps();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                tvPermissionHint.setVisibility(View.GONE);
                loadAllInstalledApps();
                Toast.makeText(this, "权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                tvPermissionHint.setVisibility(View.VISIBLE);
                Toast.makeText(this, "需要存储权限来读取图片", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void loadAllInstalledApps() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                allAppList = new ArrayList<>();
                PackageManager pm = getPackageManager();

                try {
                    // 方法1: 使用传统的应用列表获取方式
                    List<ApplicationInfo> packages = pm.getInstalledApplications(0);
                    Set<String> addedPackages = new HashSet<>();

                    for (ApplicationInfo packageInfo : packages) {
                        // 只显示用户安装的应用，排除系统应用
                        if ((packageInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                            CharSequence label = pm.getApplicationLabel(packageInfo);
                            String appName = (label != null) ? label.toString() : packageInfo.packageName;
                            String packageName = packageInfo.packageName;

                            // 避免重复添加
                            if (!addedPackages.contains(packageName) && !isSystemCoreApp(packageName)) {
                                try {
                                    // 检查应用是否被禁用
                                    int enabledState = pm.getApplicationEnabledSetting(packageName);
                                    if (enabledState != PackageManager.COMPONENT_ENABLED_STATE_DISABLED &&
                                        enabledState != PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
                                        
                                        Drawable appIcon = pm.getApplicationIcon(packageName);
                                        allAppList.add(new AppInfo(appName, packageName, appIcon));
                                        addedPackages.add(packageName);
                                    }
                                } catch (PackageManager.NameNotFoundException e) {
                                    // 忽略无法获取图标的应用
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    // 如果上述方法失败，使用Intent查询方式
                    loadAppsUsingIntent(pm);
                }

                // 回到主线程更新UI
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        onAppListLoaded();
                    }
                });
            }
        }).start();
    }

    private void loadAppsUsingIntent(PackageManager pm) {
        try {
            // 使用Intent查询常见的应用类型
            Intent[] intents = {
                    new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER),
                    new Intent(Intent.ACTION_VIEW).setType("image/*"),
                    new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
                    new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
                    new Intent(MediaStore.ACTION_VIDEO_CAPTURE)
            };

            Set<String> addedPackages = new HashSet<>();

            for (Intent intent : intents) {
                try {
                    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
                    for (ResolveInfo resolveInfo : resolveInfos) {
                        if (resolveInfo.activityInfo != null) {
                            ApplicationInfo appInfo = resolveInfo.activityInfo.applicationInfo;
                            String packageName = appInfo.packageName;

                            if (!addedPackages.contains(packageName) &&
                                    (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 &&
                                    !isSystemCoreApp(packageName)) {

                                try {
                                    // 检查应用是否被禁用
                                    int enabledState = pm.getApplicationEnabledSetting(packageName);
                                    if (enabledState != PackageManager.COMPONENT_ENABLED_STATE_DISABLED &&
                                        enabledState != PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
                                        
                                        CharSequence label = resolveInfo.loadLabel(pm);
                                        String appName = (label != null) ? label.toString() : packageName;
                                        Drawable appIcon = resolveInfo.loadIcon(pm);
                                        allAppList.add(new AppInfo(appName, packageName, appIcon));
                                        addedPackages.add(packageName);
                                    }
                                } catch (Exception e) {
                                    // 忽略无法处理的应用
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    // 忽略单个Intent查询失败
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void onAppListLoaded() {
        if (allAppList == null || allAppList.isEmpty()) {
            // 如果还是空，添加一些常见的图片应用
            addCommonImageApps();
        }

        // 按应用名称排序
        Collections.sort(allAppList, new Comparator<AppInfo>() {
            @Override
            public int compare(AppInfo app1, AppInfo app2) {
                return app1.getAppName().compareToIgnoreCase(app2.getAppName());
            }
        });

        // 添加"所有图片"选项
        allAppList.add(0, new AppInfo("所有图片", "all_images",
                ContextCompat.getDrawable(this, android.R.drawable.ic_menu_gallery)));

        // 添加"系统相册"选项
        allAppList.add(1, new AppInfo("系统相册", "system_gallery",
                ContextCompat.getDrawable(this, android.R.drawable.ic_menu_camera)));

        updateAppSelectionUI();

        if (allAppList.size() > 2) {
            Toast.makeText(this, "已加载 " + (allAppList.size() - 2) + " 个用户应用", Toast.LENGTH_SHORT).show();
        }
    }

    private void addCommonImageApps() {
        // 手动添加一些常见的图片应用包名和名称
        String[][] commonApps = {
                {"Ugirls尤果", "com.example.tupiancs33"},
                {"QQ", "com.tencent.mobileqq"},
                {"微博", "com.sina.weibo"},
                {"抖音", "com.ss.android.ugc.aweme"},
                {"快手", "com.kuaishou.nebula"},
                {"美图秀秀", "com.mt.mtxx.mtxx"},
                {"小红书", "com.xingin.xhs"},
                {"知乎", "com.zhihu.android"},
                {"B站", "tv.danmaku.bili"},
                {"淘宝", "com.taobao.taobao"},
                {"支付宝", "com.eg.android.AlipayGphone"},
                {"钉钉", "com.alibaba.android.rimet"},
                {"百度网盘", "com.baidu.netdisk"},
                {"WPS", "cn.wps.moffice_eng"},
                {"UC浏览器", "com.UCMobile"},
                {"360浏览器", "com.qihoo.browser"}
        };

        for (String[] app : commonApps) {
            String appName = app[0];
            String packageName = app[1];
            allAppList.add(new AppInfo(appName, packageName,
                    ContextCompat.getDrawable(this, android.R.drawable.sym_def_app_icon)));
        }
    }

    private boolean isSystemCoreApp(String packageName) {
        // 排除一些系统核心应用
        String[] systemApps = {
                "android",
                "com.android.settings",
                "com.android.systemui",
                "com.google.android.gms",
                "com.android.providers",
                "com.android.vending",
                "com.google.android.providers",
                "com.android.phone",
                "com.google.android",
                "com.qualcomm",
                "com.huawei",
                "com.xiaomi",
                "com.oppo",
                "com.vivo",
                "com.samsung"
        };

        for (String systemApp : systemApps) {
            if (packageName.startsWith(systemApp)) {
                return true;
            }
        }
        return false;
    }

    private void updateAppSelectionUI() {
        if (selectedApp != null) {
            tvSelectedApp.setText("已选择: " + selectedApp.getAppName());
            tvSelectedApp.setVisibility(View.VISIBLE);
        } else {
            tvSelectedApp.setVisibility(View.GONE);
        }
    }

    private void setupSeekBar() {
        seekBarInterval.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                currentSwitchInterval = progress + 1;
                tvInterval.setText(currentSwitchInterval + "秒");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    private void setupButtons() {
        btnSelectApp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAppSelection();
            }
        });

        btnBrowse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadAssetsImagesFromContentProvider();
            }
        });

        btnAutoPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imageList.isEmpty()) {
                    Toast.makeText(MainActivity.this, "没有找到图片", Toast.LENGTH_SHORT).show();
                    return;
                }
                openAutoPlay();
            }
        });
    }

    private void openAppSelection() {
        if (allAppList == null || allAppList.isEmpty()) {
            Toast.makeText(this, "正在加载应用列表...", Toast.LENGTH_SHORT).show();
            loadAllInstalledApps();
            return;
        }

        Intent intent = new Intent(this, AppSelectionActivity.class);
        intent.putParcelableArrayListExtra("APP_LIST", new ArrayList<>(allAppList));
        startActivityForResult(intent, APP_SELECTION_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == APP_SELECTION_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                selectedApp = data.getParcelableExtra("SELECTED_APP");
                updateAppSelectionUI();
                loadAppImages();
            }
        }
    }

    private void loadAppImages() {
        imageList.clear();
        previewAdapter.setImageList(imageList);

        if (selectedApp == null) {
            return;
        }

        // 显示加载提示
        Toast.makeText(this, "正在搜索图片...", Toast.LENGTH_SHORT).show();

        // 在新线程中加载图片，避免阻塞UI
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 如果是"所有图片"选项，搜索所有目录
                if ("all_images".equals(selectedApp.getPackageName())) {
                    loadAllImages();
                } else if ("system_gallery".equals(selectedApp.getPackageName())) {
                    // 系统相册选项
                    loadSystemGalleryImages();
                } else {
                    // 根据选择的应用程序加载对应的图片
                    loadImagesForApp(selectedApp.getPackageName());
                    
                    // 如果是tupiancs34应用，尝试通过ContentProvider访问assets图片
                    if ("com.example.tupiancs34".equals(selectedApp.getPackageName())) {
                        loadAssetsImagesFromContentProvider();
                    }
                }

                // 回到主线程更新UI
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        previewAdapter.setImageList(imageList);

                        if (imageList.isEmpty()) {
                            Toast.makeText(MainActivity.this, "该应用没有找到图片", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "找到 " + imageList.size() + " 张图片", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    private void loadAllImages() {
        // 搜索多个常见的图片目录
        searchImagesInDirectory(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES));
        searchImagesInDirectory(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM));
        searchImagesInDirectory(new File(Environment.getExternalStorageDirectory(), "Download"));
        searchImagesInDirectory(new File(Environment.getExternalStorageDirectory(), "WeiXin"));
        searchImagesInDirectory(new File(Environment.getExternalStorageDirectory(), "Tencent"));
        searchImagesInDirectory(new File(Environment.getExternalStorageDirectory(), "Screenshots"));
        searchImagesInDirectory(new File(Environment.getExternalStorageDirectory(), "相册"));
        searchImagesInDirectory(new File(Environment.getExternalStorageDirectory(), "Camera"));
    }

    private void loadSystemGalleryImages() {
        // 专门搜索系统相册相关的目录
        searchImagesInDirectory(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM));
        searchImagesInDirectory(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES));
        searchImagesInDirectory(new File(Environment.getExternalStorageDirectory(), "DCIM/Camera"));
        searchImagesInDirectory(new File(Environment.getExternalStorageDirectory(), "Pictures/Screenshots"));
    }

    private void loadImagesForApp(String packageName) {
        // 根据包名推测可能的图片目录
        File externalStorage = Environment.getExternalStorageDirectory();

        // 常见的应用图片目录模式
        String[] possiblePaths = {
                packageName,
                "Android/data/" + packageName,
                "Android/data/" + packageName + "/assets_images", // assets复制的图片
                "Pictures/" + packageName,
                "DCIM/" + packageName,
                "Tencent/MicroMsg/WeiXin", // 微信
                "Tencent/QQ_Images",        // QQ
                "Pictures/Weibo",           // 微博
                "DCIM/Camera",              // 相机
                "Pictures/Screenshots",     // 截图
                "Pictures/Instagram",       // Instagram
                "Pictures/Snapchat",        // Snapchat
                "Pictures/" + packageName,
                "Documents/" + packageName,
        };

        for (String path : possiblePaths) {
            File dir = new File(externalStorage, path);
            searchImagesInDirectory(dir);
        }

        // 尝试通过ContentProvider访问其他应用的图片（如果支持）
        loadImagesFromContentProvider(packageName);

        // 如果没找到图片，尝试搜索整个存储
        if (imageList.isEmpty()) {
            loadAllImages();
        }
    }

    private void searchImagesInDirectory(File directory) {
        if (directory == null || !directory.exists() || !directory.isDirectory()) {
            return;
        }

        try {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        // 递归搜索子目录（限制深度）
                        if (getDepth(file) < 10) { // 限制递归深度为3层
                            searchImagesInDirectory(file);
                        }
                    } else if (isImageFile(file)) {
                        imageList.add(new ImageItem(file.getAbsolutePath(), file.getName()));
                    }
                }
            }
        } catch (SecurityException e) {
            // 忽略没有权限的目录
        }
    }

    private int getDepth(File file) {
        int depth = 0;
        File parent = file.getParentFile();
        while (parent != null) {
            depth++;
            parent = parent.getParentFile();
        }
        return depth;
    }

    private boolean isImageFile(File file) {
        if (file.isDirectory()) return false;
        String name = file.getName().toLowerCase();
        return name.endsWith(".jpg") || name.endsWith(".jpeg") ||
                name.endsWith(".png") || name.endsWith(".gif") ||
                name.endsWith(".bmp") || name.endsWith(".webp");
    }

    private void loadImagesFromContentProvider(String packageName) {
        try {
            // 尝试通过MediaStore查询图片
            Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            String[] projection = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DISPLAY_NAME};
            String selection = MediaStore.Images.Media.DATA + " LIKE ?";
            String[] selectionArgs = {"%" + packageName + "%"};
            
            Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, null);
            
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                    String imageName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME));
                    
                    if (imagePath != null && new File(imagePath).exists()) {
                        imageList.add(new ImageItem(imagePath, imageName));
                    }
                }
                cursor.close();
            }
        } catch (Exception e) {
            // 忽略ContentProvider访问失败
        }
    }

    private void loadAssetsImagesFromContentProvider() {
        Log.d(TAG, "开始加载所有base64图片...");
        
        // 清空现有的图片列表
        imageList.clear();

        try {
            Uri baseUri = Uri.parse("content://com.example.tupiancs34.provider/images");
            ContentResolver resolver = getContentResolver();

            // 请求包含base64数据的列
            String[] projection = {"_display_name", "_size", "base64_data"};
            android.database.Cursor cursor = resolver.query(baseUri, null, null, null, null);
            
            if (cursor != null) {
                int count = cursor.getCount();
                Log.d(TAG, "发现 " + count + " 张图片，开始处理...");

                if (count > 0) {
                    cursor.moveToFirst();
                    int successCount = 0;
                    int failCount = 0;
                    
                    do {
                        String fileName = cursor.getString(cursor.getColumnIndex("_display_name"));
                        long fileSize = cursor.getLong(cursor.getColumnIndex("_size"));
                        String base64Data = cursor.getString(cursor.getColumnIndex("base64_data"));

                        Log.d(TAG, "处理图片: " + fileName + ", 大小: " + fileSize + " bytes, base64长度: " +
                                (base64Data != null ? base64Data.length() : 0));

                        // 检查是否是图片文件
                        if (fileName != null && isImageFileName(fileName) && base64Data != null && !base64Data.isEmpty()) {
                            try {
                                // 将base64字符串转换为字节数组
                                byte[] imageBytes = Base64.decode(base64Data, Base64.DEFAULT);
                                Log.d(TAG, "base64解码成功，字节数组长度: " + imageBytes.length);

                                // 使用BitmapFactory从字节数组创建Bitmap
                                BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inJustDecodeBounds = true;
                                BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, options);
                                
                                if (options.outWidth > 0 && options.outHeight > 0) {
                                    Log.d(TAG, "图片尺寸: " + options.outWidth + "x" + options.outHeight);
                                    
                                    // 创建ImageItem并添加到列表
                                    String imageUri = "content://com.example.tupiancs34.provider/images/" + fileName;
                                    ImageItem imageItem = new ImageItem(imageUri, fileName, base64Data);
                                    
                                    // 将base64数据存储到ImageItem中，这样适配器可以直接使用
                                    imageList.add(imageItem);
                                    successCount++;
                                    
                                    Log.d(TAG, "✅ 成功添加图片: " + fileName);
                                } else {
                                    Log.e(TAG, "❌ 无法解析图片尺寸: " + fileName);
                                    failCount++;
                                }
                            } catch (Exception e) {
                                Log.e(TAG, "❌ 处理图片 " + fileName + " 时出错: " + e.getMessage());
                                failCount++;
                            }
                        } else {
                            Log.d(TAG, "跳过非图片文件或base64数据为空: " + fileName);
                        }
                    } while (cursor.moveToNext());

                    Log.d(TAG, "图片处理完成 - 成功: " + successCount + ", 失败: " + failCount);
                    
                    // 更新适配器
                    int finalSuccessCount = successCount;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            previewAdapter.notifyDataSetChanged();
                            Toast.makeText(MainActivity.this, 
                                    "✅ 成功加载 " + finalSuccessCount + " 张图片",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    Log.d(TAG, "没有找到图片");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                cursor.close();
            } else {
                Log.e(TAG, "无法查询ContentProvider");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "❌ 无法访问ContentProvider", Toast.LENGTH_SHORT).show();
                    }
                });
            }

        } catch (SecurityException e) {
            Log.e(TAG, "权限错误: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "❌ 权限错误: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "加载图片时出错", e);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "❌ 加载失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
        }
    }
    
    private boolean isImageFileName(String fileName) {
        if (fileName == null) return false;
        String lowerCase = fileName.toLowerCase();
        return lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg") ||
               lowerCase.endsWith(".png") || lowerCase.endsWith(".gif") ||
               lowerCase.endsWith(".bmp") || lowerCase.endsWith(".webp");
    }

    private void openImageBrowser() {
        Intent intent = new Intent(this, AutoPlayActivity.class);
        intent.putExtra("MODE", "BROWSE");
        intent.putExtra("INTERVAL", currentSwitchInterval);
        intent.putExtra("APP_NAME", selectedApp != null ? selectedApp.getAppName() : "未知应用");
        startActivity(intent);
    }

    private void openAutoPlay() {
        Intent intent = new Intent(this, AutoPlayActivity.class);
        intent.putExtra("MODE", "AUTO_PLAY");
        intent.putExtra("INTERVAL", currentSwitchInterval);
        intent.putExtra("APP_NAME", selectedApp != null ? selectedApp.getAppName() : "未知应用");
        startActivity(intent);
    }


    // 兼容旧版本的方法
    private ArrayList<String> getImagePaths() {
        ArrayList<String> paths = new ArrayList<>();
        for (ImageItem item : imageList) {
            paths.add(item.getImagePath());
        }
        return paths;
    }

    // 数据模型类 - 实现Parcelable以便在Activity间传递
    public static class AppInfo implements android.os.Parcelable {
        private String appName;
        private String packageName;
        private transient Drawable appIcon;

        public AppInfo(String appName, String packageName, Drawable appIcon) {
            this.appName = appName;
            this.packageName = packageName;
            this.appIcon = appIcon;
        }

        protected AppInfo(android.os.Parcel in) {
            appName = in.readString();
            packageName = in.readString();
        }

        public static final Creator<AppInfo> CREATOR = new Creator<AppInfo>() {
            @Override
            public AppInfo createFromParcel(android.os.Parcel in) {
                return new AppInfo(in);
            }

            @Override
            public AppInfo[] newArray(int size) {
                return new AppInfo[size];
            }
        };

        public String getAppName() { return appName; }
        public String getPackageName() { return packageName; }
        public Drawable getAppIcon() { return appIcon; }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(android.os.Parcel dest, int flags) {
            dest.writeString(appName);
            dest.writeString(packageName);
        }

        @Override
        public String toString() {
            return appName;
        }
    }

    public static class ImageItem {
        private String imagePath;
        private String imageName;
        private String base64Data; // 存储base64数据

        public ImageItem(String imagePath, String imageName) {
            this.imagePath = imagePath;
            this.imageName = imageName;
        }

        public ImageItem(String imagePath, String imageName, String base64Data) {
            this.imagePath = imagePath;
            this.imageName = imageName;
            this.base64Data = base64Data;
        }

        public String getImagePath() { return imagePath; }
        public String getImageName() { return imageName; }
        public String getBase64Data() { return base64Data; }
        public void setBase64Data(String base64Data) { this.base64Data = base64Data; }
    }
}